package com.example.fragment;

import java.util.ArrayList;
import java.util.List;

import com.example.Utils.DBUtil;
import com.example.Utils.Utilsquxian;
import com.example.application.MyApplication;
import com.example.entity.DbWeather;
import com.example.entity.Future;
import com.example.entity.Sk;
import com.example.entity.Today;
import com.example.entity.Weather;
import com.example.weatherforcast.CityActivity;
import com.example.weatherforcast.R;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;

public class MainFragment extends Fragment implements OnClickListener {
	
	private static final int MESSAGE_REFRESH_DATA = 0x0001;
	
	private LineChartView lineChart, lineChartDay;
	private List<PointValue> mPointValues = new ArrayList<PointValue>();
	private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
	private int[] tempGrapt = new int[24];
	private int[] lowArray = new int[8], highArray = new int[8];
	private String[] timeGrapt = new String[24], dateArray = new String[8];
	private List<String> weatherlist, weeklist, datelist;
	private List<Integer> Lowlist, Highlist;
	List<Line> list = null;
	private Utilsquxian quxian;
	private DbWeather dbweather;
	private SharedPreferences mpreferences;
	private static boolean flag = true;
	private String area;
	View view;
	LinearLayout ll_mainfragment;
	TextView tv_weather, tv_temp, tv_air, tv_air1, tv_todayweather,
			tv_todaytemp, tv_tomorrowweather, tv_tomorrowtemp, tv_thirdDay,
			tv_fourday, tv_fiveDay, tv_sixDay, tv_sevenDay, tv_firstDate,
			tv_secondDate, tv_thirdDate, tv_fourDate, tv_fiveDate, tv_sixDate,
			tv_sevenDate, tv_firstWeather, tv_secondWeather, tv_thirdWeather,
			tv_fourWeather, tv_fiveWeather, tv_sixWeather, tv_sevenWeather;
	Button btn_car, btn_hot, btn_travel, btn_uv, btn_sport, btn_search;
	private MyApplication mapplication;
	private SQLiteDatabase db;

	private Sk sk;
	private Today today;
	private Future firstDay, tomorrow, thirdDay, fourDay, fiveDay, sixDay,
			sevenDay;
	
	private Handler mHandler;

	public static MainFragment newInstances(String area) {
		MainFragment f = new MainFragment();
		Bundle bundle = new Bundle();
		bundle.putString("city", area);
		f.setArguments(bundle);
		return f;

	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_main, null);
		mHandler = new Handler();
		initView();

		Bundle bundle = getArguments();
		area = bundle.getString("city");
		initDate();
		refreshData();
		return view;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		btn_search.setOnClickListener(this);

	}
	
	@Override
	public void onResume() {
		super.onResume();
		delayRefreshData();
	}
/**
 * 每20秒刷新一次
 */
	private void delayRefreshData(){
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				refreshData();
				delayRefreshData();
			}
		}, 80000);
	}

	private void initView() {
		// TODO Auto-generated method stub
		ll_mainfragment = (LinearLayout) view
				.findViewById(R.id.ll_mainfragment);
		lineChart = (LineChartView) view.findViewById(R.id.line_chart);
		lineChartDay = (LineChartView) view.findViewById(R.id.lchart_weather);
		tv_temp = (TextView) view.findViewById(R.id.tv_temp);
		tv_weather = (TextView) view.findViewById(R.id.tv_weather);
		tv_air = (TextView) view.findViewById(R.id.tv_air);
		tv_air1 = (TextView) view.findViewById(R.id.tv_air1);
		tv_todayweather = (TextView) view.findViewById(R.id.tv_todayweather);
		tv_todaytemp = (TextView) view.findViewById(R.id.tv_todaytemp);
		tv_tomorrowweather = (TextView) view
				.findViewById(R.id.tv_tomorrowweather);
		tv_tomorrowtemp = (TextView) view.findViewById(R.id.tv_tomorrowtemp);
		tv_thirdDay = (TextView) view.findViewById(R.id.tv_thirdday);
		tv_fourday = (TextView) view.findViewById(R.id.tv_fourday);
		tv_fiveDay = (TextView) view.findViewById(R.id.tv_fiveday);
		tv_sixDay = (TextView) view.findViewById(R.id.tv_sixday);
		tv_sevenDay = (TextView) view.findViewById(R.id.tv_sevenday);
		tv_firstDate = (TextView) view.findViewById(R.id.tv_firstdate);
		tv_secondDate = (TextView) view.findViewById(R.id.tv_seconddate);
		tv_thirdDate = (TextView) view.findViewById(R.id.tv_thirddate);
		tv_fourDate = (TextView) view.findViewById(R.id.tv_fourdate);
		tv_fiveDate = (TextView) view.findViewById(R.id.tv_fivedate);
		tv_sixDate = (TextView) view.findViewById(R.id.tv_sixdate);
		tv_sevenDate = (TextView) view.findViewById(R.id.tv_sevendate);
		tv_firstWeather = (TextView) view.findViewById(R.id.tv_firstweather);
		tv_secondWeather = (TextView) view.findViewById(R.id.tv_secondweather);
		tv_thirdWeather = (TextView) view.findViewById(R.id.tv_thirdweather);
		tv_fourWeather = (TextView) view.findViewById(R.id.tv_fourweather);
		tv_fiveWeather = (TextView) view.findViewById(R.id.tv_fiveweather);
		tv_sixWeather = (TextView) view.findViewById(R.id.tv_sixweather);
		tv_sevenWeather = (TextView) view.findViewById(R.id.tv_sevenweather);
		btn_car = (Button) view.findViewById(R.id.btn_car);
		btn_hot = (Button) view.findViewById(R.id.btn_hot);
		btn_sport = (Button) view.findViewById(R.id.btn_sport);
		btn_travel = (Button) view.findViewById(R.id.btn_travel);
		btn_uv = (Button) view.findViewById(R.id.btn_uv);
		btn_search = (Button) view.findViewById(R.id.btn_searchfragment);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_searchfragment:
			Intent intent = new Intent(getActivity(), CityActivity.class);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.opencity,
					R.anim.opensecond);
			break;

		default:
			break;
		}
	}

	private void initDate() {
		// TODO Auto-generated method stub
		mapplication = MyApplication.getInstance();
		db = mapplication.getDb();
		mpreferences = mapplication.getMpreferences();
		// db=DbUtils.create(getActivity());

		quxian = new Utilsquxian();
		weatherlist = new ArrayList<String>();
		weeklist = new ArrayList<String>();
		datelist = new ArrayList<String>();
		Lowlist = new ArrayList<Integer>();
		Highlist = new ArrayList<Integer>();
	}

	/**
	 * 发送网络数据,并对界面进行赋值
	 * 
	 */
	public void getDataFromNetwork() {
		// TODO Auto-generated method stub
		String url = "http://v.juhe.cn/weather/index?key=e01e8df1e750b0704d196d678eff84ac&format=2&cityname="
				+ area;
		HttpUtils http = new HttpUtils();

		http.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				getDataFromLocal();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				Gson gson = new Gson();
				Weather weather = gson.fromJson(arg0.result, Weather.class);
				if (weather.getReason().equals("successed!")) {
					flag = mpreferences.getBoolean(area, true);

					if (flag) {
						Editor editor = mpreferences.edit();
						editor.putBoolean(area, false);
						editor.commit();
						dbweather = new DbWeather(arg0.result, area);
						DBUtil.insert(db, dbweather);
					} else {
						dbweather = new DbWeather(arg0.result, area);
						dbweather = new DbWeather(arg0.result, area);
						DBUtil.update(db, dbweather);
					}

					sk = weather.getResult().getSk();
					today = weather.getResult().getToday();
					firstDay = weather.getResult().getFuture().get(0);
					tomorrow = weather.getResult().getFuture().get(1);
					thirdDay = weather.getResult().getFuture().get(2);
					fourDay = weather.getResult().getFuture().get(3);
					fiveDay = weather.getResult().getFuture().get(4);
					sixDay = weather.getResult().getFuture().get(5);
					sevenDay = weather.getResult().getFuture().get(6);
					setViewData(sk, today, firstDay, tomorrow, thirdDay,
							fourDay, fiveDay, sixDay, sevenDay);
				}

			}
		});
	}

	/**
	 * 得到未来某一天的天气情况
	 * 
	 * @param future
	 */
	private void GetFutureWeather(Future future) {
		String week = future.getWeek();
		weeklist.add(week);
		String date1 = future.getDate();
		String date = date1.substring(4, 6) + "/" + date1.substring(6, 8);
		datelist.add(date);
		String weather1 = future.getWeather();
		String weather = weather1.substring(weather1.indexOf("转") + 1,
				weather1.length());
		weatherlist.add(weather);
		String temperature = future.getTemperature();
		String temperatureLow = temperature.substring(0,
				temperature.indexOf("℃"));
		int low = Integer.parseInt(temperatureLow);

		Lowlist.add(low);
		String temperatureHigh = temperature.substring(
				temperature.indexOf("~") + 1, temperature.length() - 1);
		int high = Integer.parseInt(temperatureHigh);
		Highlist.add(high);
	}

	/**
	 * 对曲线图中数值进行初始化
	 * 
	 * @param time
	 * @param temp
	 * @param low
	 * @param high
	 */
	private void SetData(String time, int temp, int low, int high) {
		// TODO Auto-generiated method stub
		String[] st = { "01:00", "02:00", "03:00", "04:00", "05:00", "06:00",
				"07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00",
				"14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00",
				"21:00", "22:00", "23:00", "24:00" };// X轴的标注

		int num = 0;
		List<String> slist = new ArrayList<String>();
		for (int i = 0; i < st.length; i++) {
			if (st[i].equals(time)) {
				num = i;
			}
		}

		for (int i = num; i < st.length; i++) {

			if (i == num) {
				tempGrapt[0] = temp;
				slist.add("当前");
			} else
				slist.add(st[i]);
			if (i == 11) {
				tempGrapt[slist.size() - 1] = high;
			}
			if (i == 23) {
				tempGrapt[slist.size() - 1] = low;
			}
		}
		for (int i = 0; i < num; i++) {
			slist.add(st[i]);
			if (i == 11) {
				tempGrapt[slist.size() - 1] = high;
			}
			if (i == 23) {
				tempGrapt[slist.size() - 1] = low;
			}
		}
		for (int i = 0; i < st.length; i++) {
			timeGrapt[i] = slist.get(i);
		}

		if (num == 11 || num == 23) {
			tempGrapt[23] = temp;
			tempGrapt[0] = temp;
		} else if (num > 0) {
			tempGrapt[23] = temp;
		}

	}

	/**
	 * 根据外部提供的数值对界面进行赋值
	 * 
	 * @param sk
	 * @param today
	 * @param firstDay
	 * @param tomorrow
	 * @param thirdDay
	 * @param fourDay
	 * @param fiveDay
	 * @param sixDay
	 * @param sevenDay
	 */
	private void setViewData(Sk sk, Today today, Future firstDay,
			Future tomorrow, Future thirdDay, Future fourDay, Future fiveDay,
			Future sixDay, Future sevenDay) {
		weatherlist.clear();
		Highlist.clear();
		Lowlist.clear();
		weeklist.clear();
		datelist.clear();

		String temp = sk.getTemp();
		String time1 = sk.getTime();
		time1 = time1.substring(0, 2);
		String time = time1 + ":00";
		int num = Integer.parseInt(temp);// 根据当前温度得到现在温度int类型
		String wind_direction = sk.getWind_direction();
		String wind_strength = sk.getWind_strength();
		String weather1 = today.getWeather();
		String back;
		int settime = Integer.parseInt(time1);

		// 000

		String temperature = today.getTemperature();
		String temperatureLow = temperature.substring(0,
				temperature.indexOf("℃"));
		int low = Integer.parseInt(temperatureLow);

		String temperatureHigh = temperature.substring(
				temperature.indexOf("~") + 1, temperature.length() - 1);
		int high = Integer.parseInt(temperatureHigh);

		SetData(time, num, low, high);// 得到曲线图的数值

		list = new ArrayList<Line>();
		list.add(quxian.getLine(tempGrapt));
		quxian.getLine(tempGrapt).setColor(Color.parseColor("#80FFFF"));
		quxian.initData(lineChart, list, timeGrapt);// 24小时天气预报曲线图
		lineChart.clearAnimation();
		String car = today.getWash_index();
		String hot = today.getDressing_index();
		String travel = today.getTravel_index();
		String sport = today.getExercise_index();
		String uv = today.getUv_index();
		String tomorrow_weather = tomorrow.getWeather();
		String tomorrow_temperature = tomorrow.getTemperature();
		tv_temp.setText(temp);
		tv_weather.setText(weather1);
		// Log.i("XYH","weather1"+ weather1+"DDD"+temperature);
		tv_air.setText(wind_direction);
		tv_air1.setText(wind_strength);
		tv_todayweather.setText(weather1);
		tv_todaytemp.setText(temperature);
		tv_tomorrowweather.setText(tomorrow_weather);
		tv_tomorrowtemp.setText(tomorrow_temperature);
		// Log.i("XYH","tomorrow_temperature"+tomorrow_temperature);
		GetFutureWeather(firstDay);
		GetFutureWeather(tomorrow);
		GetFutureWeather(thirdDay);
		GetFutureWeather(fourDay);
		GetFutureWeather(fiveDay);
		GetFutureWeather(sixDay);
		GetFutureWeather(sevenDay);
		GetFutureWeather(firstDay);
		for (int i = 0; i < Lowlist.size(); i++) {
			lowArray[i] = Lowlist.get(i);
			highArray[i] = Highlist.get(i);
			dateArray[i] = weeklist.get(i);
		}
		list = new ArrayList<Line>();
		quxian.getLine(lowArray).setColor(Color.parseColor("#80FFFF"));
		quxian.getLine(highArray).setColor(Color.GRAY);
		list.add(quxian.getLine(lowArray));
		quxian.getLine(highArray).setColor(Color.GRAY);
		list.add(quxian.getLine(highArray));
		quxian.initData(lineChartDay, list, dateArray);// 一周天气预报曲线图

		tv_thirdDay.setText(weeklist.get(2));
		tv_fourday.setText(weeklist.get(3));
		tv_fiveDay.setText(weeklist.get(4));
		tv_sixDay.setText(weeklist.get(5));
		tv_sevenDay.setText(weeklist.get(6));
		tv_firstDate.setText(datelist.get(0));
		tv_secondDate.setText(datelist.get(1));
		tv_thirdDate.setText(datelist.get(2));
		tv_fourDate.setText(datelist.get(3));
		tv_fiveDate.setText(datelist.get(4));
		tv_sixDate.setText(datelist.get(5));
		tv_sevenDate.setText(datelist.get(6));
		tv_firstWeather.setText(weatherlist.get(0));

		tv_secondWeather.setText(weatherlist.get(1));
		tv_thirdWeather.setText(weatherlist.get(2));
		tv_fourWeather.setText(weatherlist.get(3));
		tv_fiveWeather.setText(weatherlist.get(4));
		tv_sixWeather.setText(weatherlist.get(5));
		tv_sevenWeather.setText(weatherlist.get(6));
		btn_car.setText("洗车" + "\n" + car);
		btn_hot.setText("天气" + "\n" + hot);
		btn_travel.setText("旅行" + "\n" + travel);
		btn_sport.setText("户外" + "\n" + sport);
		btn_uv.setText("紫外线" + "\n" + uv);

	}

	/**
	 * 没有网络时查询数据库保存的天气信息 并保存到天气信息中
	 * 
	 * @param area
	 */
	public void getDataFromLocal() {
		// TODO Auto-generated method stub
		String data = DBUtil.querySingle(db, area);

		if (data != null) {
			Gson gson = new Gson();
			Weather weather = gson.fromJson(data, Weather.class);

			sk = weather.getResult().getSk();
			today = weather.getResult().getToday();
			firstDay = weather.getResult().getFuture().get(0);
			tomorrow = weather.getResult().getFuture().get(1);
			thirdDay = weather.getResult().getFuture().get(2);
			fourDay = weather.getResult().getFuture().get(3);
			fiveDay = weather.getResult().getFuture().get(4);
			sixDay = weather.getResult().getFuture().get(5);
			sevenDay = weather.getResult().getFuture().get(6);
			setViewData(sk, today, firstDay, tomorrow, thirdDay, fourDay,
					fiveDay, sixDay, sevenDay);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		mHandler.removeCallbacksAndMessages(null);
	}

	private boolean isNetwrokAvaliable() {

		ConnectivityManager manager = (ConnectivityManager) getActivity()
				.getSystemService(Service.CONNECTIVITY_SERVICE);
		if (manager != null) {
			NetworkInfo info = manager.getActiveNetworkInfo();// 得到活动中的网络
			if (info != null && info.isConnected()) {
				Toast.makeText(getActivity(), "11111111", Toast.LENGTH_SHORT)
						.show();

				return true;
			} else {
				Toast.makeText(getActivity(), "没有可用网络", Toast.LENGTH_SHORT)
						.show();
				return false;
			}

		}
		return false;

	}
/**
 * 对界面进行赋值
 * @return
 */
	private boolean refreshData() {
		if (isNetwrokAvaliable()) {
			getDataFromNetwork();
		} else {
			getDataFromLocal();
		}

		return false;
	}

}